/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.core;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.ContentDocument;
import com.blandware.atleap.model.core.ResourceData;
import com.blandware.atleap.model.core.ContentLocale;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.persistence.core.ContentDocumentDAO;
import com.blandware.atleap.persistence.exception.DeleteException;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;

/**
 * <p>Hibernate implementation of ContentDocumentDAO</p>
 * <p><a href="ContentDocumentDAOHibernate.java.html"><i>View Source</i></a></p>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.9 $ $Date: 2008/06/23 13:24:53 $
 */
public class ContentDocumentDAOHibernate extends ContentResourceDAOHibernate implements ContentDocumentDAO {

	/**
	 * Creates new instance of ContentDocumentDAOHibernate
	 */
	public ContentDocumentDAOHibernate() {
	}

	// ~ CRUD Methods ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.ContentDocumentDAO#createContentDocument(com.blandware.atleap.model.core.ContentDocument, com.blandware.atleap.model.core.ResourceData, com.blandware.atleap.model.core.ContentLocale)
	 */
	public Long createContentDocument(ContentDocument contentDocument, ResourceData resourceData, ContentLocale contentLocale) {
        contentDocument.setLastUpdatedDatetime(new Date());
        contentDocument.setContentLocale(contentLocale);
		contentDocument.setUsageCounter(new Integer(0));
		getHibernateTemplate().save(resourceData);
		contentDocument.setResourceData(resourceData);
		return (Long) getHibernateTemplate().save(contentDocument);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentDocumentDAO#retrieveContentDocument(Long)
	 */
	public ContentDocument retrieveContentDocument(Long contentDocumentId) {
		return (ContentDocument) getHibernateTemplate().get(ContentDocument.class, contentDocumentId);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentDocumentDAO#updateContentDocument(com.blandware.atleap.model.core.ContentDocument, com.blandware.atleap.model.core.ResourceData, com.blandware.atleap.model.core.ContentLocale)
	 */
	public void updateContentDocument(ContentDocument contentDocument, ResourceData resourceData, ContentLocale contentLocale) {
        contentDocument.setLastUpdatedDatetime(new Date());
        contentDocument.setContentLocale(contentLocale);
		getHibernateTemplate().saveOrUpdate(resourceData);
		contentDocument.setResourceData(resourceData);
		getHibernateTemplate().update(contentDocument);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentDocumentDAO#deleteContentDocument(com.blandware.atleap.model.core.ContentDocument)
	 */
	public void deleteContentDocument(ContentDocument contentDocument) throws DeleteException {
		getHibernateTemplate().delete(contentDocument);

		// break relations between roles and deleted document
		List roles = new ArrayList(contentDocument.getRoles());
		for ( int i = 0; i < roles.size(); i++ ) {
			Role role = (Role) roles.get(i);
			contentDocument.removeRole(role);
		}
	}

	// ~ Additional methods ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.ContentDocumentDAO#listContentDocuments(com.blandware.atleap.common.util.QueryInfo)
	 */
	public PartialCollection listContentDocuments(QueryInfo queryInfo) {
		String whereClause = new String();
		String orderByClause = new String();
		if ( queryInfo != null ) {
			whereClause = queryInfo.getWhereClause();
			orderByClause = queryInfo.getOrderByClause();
			if ( whereClause != null && whereClause.length() != 0 ) {
				whereClause = " where " + whereClause;
			} else {
				whereClause = new String();
			}
			if ( orderByClause != null && orderByClause.length() != 0 ) {
				orderByClause = " order by " + orderByClause;
			} else {
				orderByClause = new String();
			}
		}

		List list = null;
		Integer total = null;
		String hqlPart = null;
		hqlPart = "from ContentDocument r left outer join r.roles as role";

		hqlPart += whereClause;

		if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
			String hqlForTotal = "select count(distinct r.id) " + hqlPart;
			total = findUniqueIntegerResult(hqlForTotal);
			if ( total == null ) {
				total = new Integer(0);
			}
		}

        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
		if ( total == null || total.intValue() > 0 ) {
			String hql = "select distinct r " + hqlPart + orderByClause;
			list = executeFind(hql, queryInfo);
			if ( total == null ) {
				total = new Integer(list.size());
			}
		} else {
			list = new ArrayList();
		}
		return new PartialCollection(list, total);

	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentDocumentDAO#findContentDocumentByUri(String)
	 */
	public ContentDocument findContentDocumentByUri(String uri) {
		return (ContentDocument) findUniqueResult("from ContentDocument r where r.uri = ?", new Object[]{uri});
	}
}
